import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.Date;
import java.util.List;

public class MyServer {
    public static void main(String[] args) throws IOException {
        // try-with-resources
        try (ServerSocket ss = new ServerSocket(8080)) {
            System.out.println("服务器启动...");
            while (true) {
                Socket sock = ss.accept();
                System.out.println("接收到客户端链接：" + sock.getRemoteSocketAddress());
                Thread myThread = new MyHandler(sock);
                myThread.start();
            }
        }
    }
}

class MyHandler extends Thread {
    Socket sock;

    public MyHandler(Socket sock) {
        this.sock = sock;
    }

    public void run() {
        try (InputStream input = this.sock.getInputStream()) {
            try (OutputStream output = this.sock.getOutputStream()) {
                handle(input, output);
            }
        } catch (Exception e) {
            try {
                this.sock.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            System.out.println("client disconnected.");
        }
    }

    private void handle(InputStream input, OutputStream output) throws IOException, SQLException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
        boolean requestOk = false;
        String first = reader.readLine();
        System.out.println("==============" + first);
        if (first.startsWith("GET / HTTP/1.")) {
            requestOk = true;
        }
        if (first.startsWith("GET /ver2 HTTP/1.1")) {
            requestOk = true;
        }
        for (; ; ) {
            String header = reader.readLine();
            if (header.isEmpty()) { // 读取到空行时, HTTP Header 读取完毕
                break;
            }
            if (header.equals("sec-ch-ua-platform: \"windows\"")) {
                System.out.println("===" + header);
                requestOk = false;
                break;
            }
            System.out.println(header);
        }
        System.out.println(requestOk ? "Response OK" : "Response Error");
        if (!requestOk) {
            // 发送错误响应:
            writer.write("HTTP/1.0 404 Not Found\r\n");
            writer.write("Content-Length: 0\r\n");
            writer.write("\r\n");
            writer.flush();
        } else {
//放获取数据库的代码
//            获取数据库
            if (first.startsWith("GET / HTTP/1.")) {
                try {
                    extracted(writer);
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("Database error:" + e.getMessage());
                }
            } else if (first.startsWith("GET /ver2 HTTP/1.1")) {
                try {
                    extracted(writer);
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("Database error:" + e.getMessage());
                }
            } else {
                // 发送错误响应:
                writer.write("HTTP/1.0 404 Not Found\r\n");
                writer.write("Content-Length: 0\r\n");
                writer.write("\r\n");
                writer.flush();
            }

        }

        System.out.println("=== === ===");
    }

    private static void extracted(BufferedWriter writer) throws SQLException, IOException {
        Connection connection = getConnection();
        Statement stmt = connection.createStatement();
        String sql = "SELECT title, time, url FROM article";
        ResultSet rs = stmt.executeQuery(sql);
        StringBuilder n = new StringBuilder();

        while (rs.next()) {
            String content = rs.getString("title");
            String time = rs.getString("time");
            String url = rs.getString("url");

            String str = """
                    <div>
                        <ul class="row">
                            <li class="son-1"><a href="""
                    +
                    url
                    +
                    """
                            >
                            """
                    +
                    content
                    +
                    """
                            </a></li>
                            <li class="son-2 centers">
                            """
                    +
                    time
                    +
                    """
                                                
                            </li>
                            <li class="son-3 centers">
                            """
                    +
                    time
                    +
                    """
                                    </li>
                                </ul>
                            </div>
                            """;

            n.append(str);

        }
        // 要返回的 HTML
        String body = """
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>home-work-v1</title>
                </head>
                <style>
                                    
                    * {
                        list-style: none;
                        border: 0;
                        padding: 0;
                        margin: 0
                    }
                    .head{
                        background-color: rgb(255, 244, 230);
                        padding: 15px;
                        font-size: 25px;
                        text-align: center;
                    }
                    .overall{
                        width: 80%;
                        margin: auto;
                        border-left: 1px rgb(204, 226, 255) solid;
                        border-right: 1px rgb(204, 226, 255) solid;
                    }
                    .title{
                        font-weight: 1000;
                        border-top: 1px rgb(204, 226, 255) solid;
                        font-size: 20px;
                    }
                    .row{
                        padding-top: 5px;
                        padding-bottom: 5px;
                        background-color: #f1f1f1;
                        border-bottom:1px rgb(204, 226, 255) solid;
                        list-style-type: none;
                        display: flex;
                        width: 100%;
                                    
                    }
                    .son-1{
                        width: 50%;
                        padding: 3px;
                        border-right: 1px black solid;
                    }
                    a{
                        text-decoration: none;
                    }
                    .son-2{
                        width: 25%;
                        padding: 3px;
                        border-right: 1px black solid;
                    }
                    .son-3{
                        width: 25%;
                        padding: 3px;
                    }
                    .centers{
                        text-align: center;
                        color: #b8b5b5;
                    }
                </style>
                <body>
                <header class="head">
                    厦门小于网
                </header>
                <main>
                    <div class="overall">
                        <div>
                            <ul class="row title">
                                <li class="son-1" style="text-align: center;">标题</li>
                                <li class="son-2" style="text-align: center;">创建时间</li>
                                <li class="son-3" style="text-align: center;">更新时间</li>
                            </ul>
                        </div>
                       """
                +
                n
                +
                """
                                </div>
                        </main>
                        <footer>
                                            
                        </footer>
                        </body>
                        </html>
                        """;

        // 发送成功响应:
        writer.write("HTTP/1.1 200 OK\r\n");
        writer.write("Connection: keep-alive\r\n");
        writer.write("Content-Type: text/html\r\n");
        writer.write("Content-Length: " + body.length() + "\r\n");
        writer.write("\r\n"); // 空行标识Header和Body的分隔
        writer.write(body);
        writer.flush();
    }

    private static Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/demo01";
        String user = "root";
        String password = "lcw0909.";
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }
}
